package com.jeebey.mybatis.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.Base64Utils;

import com.jeebey.mybatis.enhance.BString;

/**MYSQL-utf8mb4-自带*/
@MappedJdbcTypes({ JdbcType.VARCHAR })
@MappedTypes({ BString.class })
public class Base64StringTypeHandler extends BaseTypeHandler<BString> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, BString parameter, JdbcType jdbcType)
			throws SQLException {
			String value = parameter.getValue() == null ? null : Base64Utils.encodeToString(parameter.getValue()
					.getBytes());
			ps.setString(i, value);
	}

	@Override
	public BString getNullableResult(ResultSet rs, String columnName) throws SQLException {
		Object object = rs.getObject(columnName);
		if (object == null) {
			return null;
		} else if (object instanceof String) {
			byte[] bytes = Base64Utils.decodeFromString((String) object);
			return new BString(bytes);
		} else {
			return null;
		}
	}

	@Override
	public BString getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		Object object = rs.getObject(columnIndex);
		if (object == null) {
			return null;
		} else if (object instanceof String) {
			byte[] bytes = Base64Utils.decodeFromString((String) object);
			return new BString(bytes);
		} else {
			return null;
		}
	}

	@Override
	public BString getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		Object object = cs.getObject(columnIndex);
		if (object == null) {
			return null;
		} else if (object instanceof String) {
			byte[] bytes = Base64Utils.decodeFromString((String) object);
			return new BString(bytes);
		} else {
			return null;
		}
	}
}
